package com.ytxg.health_management.article.service;

import com.ytxg.health_management.article.pojo.ArticleMain;
import com.ytxg.health_management.article.pojo.ArticleMx;
import com.ytxg.health_management.likeRecords.entity.LikeRecords;
import com.ytxg.health_management.article.mapper.ArticleMapper;
import com.ytxg.health_management.likeRecords.mapper.LikeRecordsMapper;
import com.ytxg.health_management.comment.mapper.CommentMapper;
import com.ytxg.health_management.mapper.SubscribeMapper;
import com.ytxg.health_management.pojo.dto.PageArticle;
import com.ytxg.health_management.pojo.dto.UserDto;
import com.ytxg.health_management.pojo.entity.*;
import com.ytxg.health_management.pojo.vo.ArticleVo;
import com.ytxg.health_management.util.Const;
import com.ytxg.health_management.util.MyException;
import com.ytxg.health_management.util.ResultCode;
import jakarta.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {

    @Resource
    ArticleMapper articleMapper;
    @Resource
    SubscribeMapper subscribeMapper;
    @Resource
    CommentMapper commentMapper;
    @Resource
    LikeRecordsMapper recordsMapper;
    @Value("${images.replace}")
    String replaceUrl;

    /**
     * 根据创建人查询文章列表
     */
    @Override
    public Result<Map<String, Object>> getListByCreateName(String createBy, Page page) {
        try {
            page.setCurrentPage((page.getCurrentPage() - 1) * page.getPageSize());
            ArticleMain select = new ArticleMain();
            select.setCreateBy(createBy).setStatus(Const.DEFAULT_ARTICLE_STATUS);
            //查询文章数量
            int total = articleMapper.selectCount(select);
            //查询文章
            List<ArticleMain> articleMains = articleMapper.selectArticleMainBase(new ArticleMain().setCreateBy(createBy), page);

            HashMap<String, Object> res = new HashMap<>();
            res.put("total", total);
            res.put("articles", articleMains);
            return Result.success(res);
        } catch (Exception e) {
            throw new MyException("查询失败" + e);
        }


    }

    /**
     * 新建文章
     */
    @Override
    public Result<String> addArticle(ArticleVo article, UserDto userDto) {

        ArticleMain articleMain = new ArticleMain();
        ArticleMx articleMx = new ArticleMx();


        //创建主表
        articleMain.setId(null)
                .setTitle(article.getTitle())
                .setUserId(userDto.getId())
                .setLike(0)
                .setSubscribe(0)
                .setArticleType(article.getType())
                .setCommentNumber(0)
                .setStatus(Const.DEFAULT_ARTICLE_STATUS)
                .setIsVip(Const.DEFAULT_ARTICLE_LEVEL)
                .setPic(article.getImg().replace(replaceUrl, ""))
                .setCreateBy(userDto.getUserName())
                .setCreateTime(new Date())
                .setUpdateTime(new Date())
                .setDelFlag(Const.DEFAULT_DEL_FLAG);

        try {
            articleMapper.insertArticleMain(articleMain);
            log.info("主表添加成功");
        } catch (Exception e) {
            return Result.fail("主表添加失败");
        }
        //创建明细
        articleMx.setLineId(articleMain.getId())
                .setText(article.getText())
                .setStatus(Const.DEFAULT_ARTICLE_STATUS)
                .setCreateBy(userDto.getUserName())
                .setCreateTime(new Date())
                .setUpdateTime(new Date())
                .setDelFlag(Const.DEFAULT_DEL_FLAG)
                .setText(article.getText());
        try {
            articleMapper.insertArticleMx(articleMx);
            log.info("从表添加成功");
        } catch (Exception e) {
            return Result.fail("从表添加失败，请检查内容是否过多");
        }

        return Result.success("添加成功", null);
    }

    /**
     * 更新文章
     */
    @Override
    public Result<String> updateArticle(ArticleVo article) {
        ArticleMain articleMain = new ArticleMain();
        ArticleMx articleMx = new ArticleMx();
        articleMain.setId(article.getId())
                .setTitle(article.getTitle())
                .setArticleType(article.getType())
                .setPic(article.getImg().replace(replaceUrl, ""))
                .setUpdateTime(new Date());
        try {
            articleMapper.updateArticleMain(articleMain);
        } catch (Exception e) {
            Result.fail("主表更新失败");
        }

        articleMx.setLineId(article.getId())
                .setText(article.getText())
                .setUpdateTime(new Date());

        try {
            articleMapper.updateArticleMx(articleMx);
        } catch (Exception e) {
            Result.fail("从表更新失败,请检查内容是否过多");
        }
        return Result.success("更新成功", null);
    }

    /**
     * 根据id删除文章
     */
    @Override
    @Transactional
    public Result<String> deleteById(List<Integer> id) {
        //删除点赞记录
        LikeRecords likeRecordsFilter = new LikeRecords();
        Subscribe subscribeFilter = new Subscribe();

        for (Integer i : id) {
            //删除文章点赞
            likeRecordsFilter.setArticleId(i);
            recordsMapper.deleteLikeRecordBase(likeRecordsFilter);
            //删除文章收藏
            subscribeFilter.setArticleId(i);
            subscribeMapper.deleteSubscribe(subscribeFilter);
        }
        //删除从表
        try {
            articleMapper.deleteArticleMx(id);
        } catch (Exception e) {
            throw new MyException("从表删除失败" + e);
        }
        //删除评论
        try {
            for (Integer i : id) {
                commentMapper.deleteCommentByArticleId(i);
            }
        } catch (Exception e) {
            throw new MyException("删除评论失败" + e);
        }
        try {
            articleMapper.deleteArticleMain(id);
        } catch (Exception e) {
            throw new MyException("删除主表失败" + e);
        }
        return Result.success("删除成功", null);
    }

    /**
     * 分页查询
     */

    @Override
    public Result<PageArticle> getPages(ArticleMain articleMain, Page page) {

        try {
            page.setCurrentPage((page.getCurrentPage() - 1) * page.getPageSize());
        } catch (Exception ignored) {
        }
        List<ArticleMain> articleMains;
        try {
            articleMains = articleMapper.selectArticleMainBase(articleMain, page);
        } catch (Exception e) {
            throw new MyException("什么情况" + e);
        }
        int total;
        try {
            total = articleMapper.selectCount(articleMain);
        } catch (Exception e) {
            throw new MyException("文章总数获取失败" + e);
        }
        PageArticle pageArticle = new PageArticle(total, articleMains);
        return Result.success(pageArticle);
    }

    /**
     * 根据id查询文章
     */
    @Override
    public Result<ArticleMain> getArticleById(int id) {
        List<ArticleMain> res = articleMapper.selectArticleMainBase(new ArticleMain().setId(id), new Page());
        if (res.isEmpty()) {
            throw new MyException(ResultCode.ARTICLE_NOT_FIND, "文章不存在");
        }
        return Result.success(res.get(0));
    }

    /**
     * 收藏文章
     */
    @Override
    public Result<String> addSubscribe(Subscribe subscribe) {
        subscribe.setCreateTime(new Date());
        try {
            subscribeMapper.insertSubscribe(subscribe);
        } catch (Exception e) {
            throw new MyException("已收藏");
        }
        try {
            articleMapper.updateSubscribe(subscribe.getArticleId());
        } catch (Exception e) {
            throw new MyException("收藏+1失败");
        }
        return Result.success("添加收藏成功", null);
    }

    /**
     * 获取收藏文章
     */
    @Override
    public Result<List<Subscribe>> getSubscribeArticle(int id) {
        try {
            List<Subscribe> subscribes = subscribeMapper.selectByUserId(id);
            return Result.success(subscribes);
        } catch (Exception e) {
            throw new MyException("获取收藏失败");
        }

    }

    /**
     * 取消收藏
     */
    @Override
    public Result<String> deleteSubscribe(int id, int articleId) {
        try {
            subscribeMapper.deleteSubscribe(new Subscribe().setId(id));
        } catch (Exception e) {
            throw new MyException("删除收藏失败");
        }
        try {
            articleMapper.deleteSubscribe(articleId);
        } catch (Exception e) {
            throw new MyException("文章收藏-1失败");

        }
        return Result.success("取消收藏成功", null);
    }

    /**
     * 文章通用查询方法
     */
    @Override
    public Result<List<ArticleMain>> searchCommon(ArticleMain articleMain) {
        List<ArticleMain> articleMains = articleMapper.selectArticleMainBase(articleMain, new Page());
        return Result.success(articleMains);
    }

    /**
     * 文章封禁
     */
    @Override
    public Result<String> articleBan(int id, String status) {

        try {
            switch (status) {
                case "1": {
                    articleMapper.articleBan(id, "2");
                    log.info("文章封禁");
                    break;
                }
                case "2": {
                    articleMapper.articleBan(id, "1");
                    log.info("文章解除封禁");
                    break;
                }
            }
        } catch (Exception e) {
            throw new MyException(Const.FAIL);
        }
        return Result.success(Const.SUCCESS,null);
    }
    /**
     * 管理员查询
     */
    @Override
    public Result<HashMap<String, Object>> getArticleAll(ArticleMain articleMain) {
        articleMain.setCurrentPage((articleMain.getCurrentPage() - 1) * articleMain.getPageSize());
        List<ArticleMain> articleMains1 = articleMapper.selectArticleAll(articleMain);
        int total = articleMapper.selectArticleAllCount(articleMain);
        HashMap<String, Object> res = new HashMap<>();
        res.put("total", total);
        res.put("articleList", articleMains1);
        return Result.success(res);
    }
    /**
     * 管理员查询
     */
    @Override
    public Result<String> toTop(ArticleMain articleMain) {
        int top = articleMapper.toTop(articleMain);
        return Result.success("操作成功");
    }
}
